#!/usr/bin/python
# -*- coding:utf-8 -*-
import ConfigParser
import os
from datetime import datetime

import MySQLdb


class HtmlOuter(object):
    def __init__(self):
        cf = ConfigParser.ConfigParser()
        cf.read('config.ini')
        db_cfg = 'db'
        if os.environ.get('DEVELOP') is not None:
            db_cfg = 'db_dev'
        host = cf.get(db_cfg, 'host')
        port = cf.get(db_cfg, 'port')
        user = cf.get(db_cfg, 'user')
        pwd = cf.get(db_cfg, 'passwd')
        db = cf.get(db_cfg, 'db')
        charset = cf.get(db_cfg, 'charset')
        self.conn = MySQLdb.connect(host=host, port=int(port), user=user, passwd=pwd, db=db, charset=charset)
        self.cursor = self.conn.cursor()

    def write(self, data):
        """
        向数据库中写入一条问题和与之相关的主题
        :param data: 问题的字典
        """
        try:
            question_id = self.__write_question(data)
            if question_id:
                for topic in data.get('topics'):
                    topic_id = self.__write_topic(topic)
                    if topic_id:
                        self.__write_question_mtm_topic(topic_id, question_id)
        except Exception, e:
            print e

    def __write_question(self, que):
        select_sql = 'select question_id from zhihu_question where question_id = %s' % int(que.get('question_id'))
        num = self.cursor.execute(select_sql)
        if num == 0:
            insert_sql = 'insert into zhihu_question(question_id, title, url, answer_num, followers_num, ' \
                         'top_answer_fn, top_answer, get_at) values(%s, %s, %s, %s, %s, %s, %s, %s)'
            param = (que.get('question_id'), que.get('title'), que.get('url'), que.get('answer_num'),
                     que.get('followers_num'), que.get('top_answer_fn'), que.get('top_answer'), str(datetime.now()))
            if self.cursor.execute(insert_sql, param) == 1:
                try:
                    self.conn.commit()
                except MySQLdb.Error:
                    return None
            else:
                return None
        return que.get('question_id')

    def __write_topic(self, topic):
        select_sql = 'select topic_id from zhihu_topic where topic_id = %d' % int(topic.get('topic_id'))
        num = self.cursor.execute(select_sql)
        if num == 0:
            insert_sql = 'insert into zhihu_topic(topic_id, name, url) values(%s, %s, %s)'
            param = (topic.get('topic_id'), topic.get('name'), topic.get('url'))
            if self.cursor.execute(insert_sql, param) == 1:
                try:
                    self.conn.commit()
                except MySQLdb.Error:
                    return None
            else:
                return None
        return topic.get('topic_id')

    def __write_question_mtm_topic(self, topic_id, question_id):
        select_sql = 'select id from zhihu_question_topic where question_id = %d and topic_id = %d' % (
            int(question_id), int(topic_id))
        num = self.cursor.execute(select_sql)
        if num == 0:
            insert_sql = 'insert into zhihu_question_topic(question_id, topic_id) values(%s, %s)'
            param = (question_id, topic_id)
            if self.cursor.execute(insert_sql, param) == 1:
                try:
                    self.conn.commit()
                except MySQLdb.Error:
                    return
